package com.hycreate.platform.modules.project;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hycreate.platform.common.config.Config;
import com.hycreate.platform.common.config.Global;
import com.hycreate.platform.common.persistence.Page;
import com.hycreate.platform.common.security.annotation.RequiresUser;
import com.hycreate.platform.common.utils.FileUtils;
import com.hycreate.platform.common.utils.StringUtils;
import com.hycreate.platform.common.utils.excel.ImportExcel;
import com.hycreate.platform.common.utils.mypage.PageDemo;
import com.hycreate.platform.common.utils.mypage.PageDemoUtil;
import com.hycreate.platform.common.web.BaseController;
import com.hycreate.platform.modules.atta.SfAttachment;
import com.hycreate.platform.modules.atta.SfAttachmentService;
import com.hycreate.platform.modules.element.SfElement;
import com.hycreate.platform.modules.element.SfElementService;
import com.hycreate.platform.modules.product.SfProduct;
import com.hycreate.platform.modules.product.SfProductService;
import com.hycreate.platform.modules.product.element.SfProductElement;
import com.hycreate.platform.modules.product.element.SfProductElementService;
import com.hycreate.platform.modules.project.product.SfProjectProduct;
import com.hycreate.platform.modules.project.product.SfProjectProductService;
import com.hycreate.platform.modules.sys.utils.DictUtils;
import com.hycreate.platform.modules.sys.utils.UserUtils;

/**
 * 项目Controller
 * 
 * @author hoader
 * @version 2017-01-09
 */
@Controller
@RequiresUser(required = false)
// 关闭登录验证，必须要加上
@RequestMapping(value = "${adminPath}/project/sfProject")
public class SfProjectController extends BaseController {

	private static String BP_SERIES = "BP"; // BP系列配件的标识

	private static int BP_TIME = 183; // 半年的年限

	private static String QC_SERIES = "QC";// QC系列配件的标识

	private static int QC_TIME = 90; // 三个月的年限

	private static int OTHER_TIME = 365; // 一年的年限

	@Autowired
	private SfProjectService sfProjectService;

	@Autowired
	private SfElementService sfElementService;

	@Autowired
	private SfProductService sfProductService;

	@Autowired
	private SfProductElementService sfProductElementService;

	@Autowired
	private SfProjectProductService sfProjectProductService;

	@Autowired
	private SfAttachmentService sfAttachmentService;

	@ModelAttribute
	public SfProject get(@RequestParam(required = false) String id) {
		SfProject entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = sfProjectService.get(id);
		}
		if (entity == null) {
			entity = new SfProject();
		}
		return entity;
	}

	@RequiresPermissions("project:sfProject:view")
	@RequestMapping(value = { "list", "" })
	public String list(SfProject sfProject, HttpServletRequest request,
			HttpServletResponse response, Model model) {

	
		
		Page pg = new Page<SfProject>(request, response);
		pg.setPageSize(30);
		Page<SfProject> page = sfProjectService.findPage(pg, sfProject);
		model.addAttribute("page", page);
		return "modules/project/sfProjectList";
	}

	/**
	 * 查找项目下面的产品
	 * @param sfProject
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("project:sfProject:view")
	@RequestMapping(value = "productlist")
	public String productlist(SfProject sfProject, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		
		return "modules/product/sfProductList";
	}
	
	
	@RequiresPermissions("project:sfProject:view")
	@RequestMapping(value = "form")
	public String form(SfProject sfProject, Model model) {
		model.addAttribute("sfProject", sfProject);
		return "modules/project/sfProjectForm";
	}

	@RequiresPermissions("project:sfProject:edit")
	@RequestMapping(value = "save")
	public String save(SfProject sfProject, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, sfProject)) {
			return form(sfProject, model);
		}
		sfProjectService.save(sfProject);
		addMessage(redirectAttributes, "保存项目成功");
		return "redirect:" + Global.getAdminPath()
				+ "/project/sfProject/?repage";
	}

	@RequiresPermissions("project:sfProject:edit")
	@RequestMapping(value = "delete")
	public String delete(SfProject sfProject,
			RedirectAttributes redirectAttributes) {
		sfProjectService.delete(sfProject);
		addMessage(redirectAttributes, "删除项目成功");
		return "redirect:" + Global.getAdminPath()
				+ "/project/sfProject/?repage";
	}

	/**
	 * 导入项目数据
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	/*导入项目的逻辑式：先把excel里的内容读取完，然后按个遍历，先对没行数据的编号做出判断，如果是空的，直接continue，
	  不是空，就继续往下执行。
	  进行第一重判断：判断项目的编号是否重复，不重复就把这条数据存入数据库中，如果重复就把这个重复的数据里面的产品类型编码数据提取出来，
	  与数据库中那个项目数据的产品编号进行对比，如果相同就是重复产品和重复项目，不保存任何数据，如果不相同就把不重复的产品数据保存。
	*/
	@RequiresPermissions("project:sfProject:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importProjectFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<SfProjectImport> list = ei.getDataList(SfProjectImport.class);

			SfProject sfProject;
			SfElement sfElement = null;
			SfProduct sfProduct = null;
			SfProjectProduct sfProjectProduct;
			SfProductElement sfProductElement;
			List<SfProject> sfProjectList = null;
			List<SfElement> sfElementList = null;
			List<SfProduct> sfProductList = null;
			List<SfProjectProduct> sfProjectProductList = null;
			List<SfProductElement> sfProductElementList = null;
			int i = 0;
			

			for (SfProjectImport sfProjectImport : list) {
				try {
					boolean isFlag = false; 

					sfProduct=null;
					/**
					 * 项目编号为空，为无效数据
					 */
					if (StringUtils.isEmpty(sfProjectImport.getProjectCode()
							.trim())) {
						failureMsg.append("<br/>项目编号为空，为无效数据; ");
						continue;
					}

					/**
					 * 项目编码已存进行对比
					 */
					sfProject = new SfProject();
					sfProject.setCode(sfProjectImport.getProjectCode().trim());
					// 通过项目编码比对是否有重复的
					sfProjectList = sfProjectService.findList(sfProject);

					if (CollectionUtils.isEmpty(sfProjectList)) {
						/**
						 * 保存项目
						 */
						sfProject.setName(sfProjectImport.getProjectName()
								.trim());
						sfProject.setCustomName(sfProjectImport
								.getProjectCustomName().trim());
						sfProject.setType(sfProjectImport.getProjectType()
								.trim());
						sfProject.setArea(sfProjectImport.getProjectArea()
								.trim());
						sfProject.setCity(sfProjectImport.getProjectCity()
								.trim());
						sfProjectService.save(sfProject);

						isFlag = true;
					} else {
						
						// 有重复的把项目集合分解，查询它有没有和产品关联
						for (SfProject sfProject2 : sfProjectList) {
							List<SfProduct> ProductList = sfProjectService
									.findProductPage(sfProject2.getId());

							// 如果有关联就再把这个产品集合分解，用sfProjectImport的产品编码比对项目里面有没有包含这个产品编码
							
						int  numb=	containing(sfProjectImport.getProductCode().trim(), ProductList);	
								
						if(numb<=0){
							
							
							SfProduct	sfProductTwo=new SfProduct();
							sfProductTwo.setCode(sfProjectImport.getProductCode().trim());
							
							sfProductList = sfProductService.findImportList(sfProductTwo);
							if (CollectionUtils.isEmpty(sfProductList)) {
								sfProductTwo.setCode(sfProjectImport.getProductCode()
										.trim());
						
								sfProductService.save(sfProductTwo);
								
							
							}
							
							
							sfProject = sfProjectList.get(0);
						 
							sfProduct=sfProductService.codeFindProduct(sfProjectImport.getProductCode().trim());
							
						}else{
							
							
							sfProject=null;
						}
							
						}
					}

					/**
					 * 判断是否需要新增产品
					 */
					if(sfProduct==null && sfProject !=null ){
					sfProduct = new SfProduct();
					sfProduct.setCode(sfProjectImport.getProductCode().trim());
					
					sfProductList = sfProductService.findImportList(sfProduct);
					if (CollectionUtils.isEmpty(sfProductList)) {
						sfProduct.setCode(sfProjectImport.getProductCode()
								.trim());
						
						
						sfProductService.save(sfProduct);
						isFlag = true;
					} else {
						
						sfProduct=sfProductService.codeFindProduct(sfProjectImport.getProductCode().trim());
						
					}
					
					}
					

					/**
					 * 判断是否需要新增项目、产品关系
					 */
					if (sfProject != null && sfProduct != null) {
						sfProjectProduct = new SfProjectProduct();
						sfProjectProduct.setProductId(sfProduct.getId());
						sfProjectProduct.setProjectId(sfProject.getId());
						sfProjectProductList = sfProjectProductService
								.findList(sfProjectProduct);
						if (CollectionUtils.isEmpty(sfProjectProductList)) {
							sfProjectProductService.save(sfProjectProduct);
							isFlag = true;
						}
					}
					if (isFlag) {
						successNum++;
					} else {
						failureMsg.append("<br/>无效数据; " + i);
					}
					
					

				} catch (Exception e) {
					e.printStackTrace();
					failureNum++;
				}
				i++;
				
				
			}
			
			
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条项目，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条数据"
					+ failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/project/sfProject/list?repage";
	}

	//查询项目的产品编码是否包含sfProjectImport里面的产品编码
	private int containing(String  sfProjectImport,
			List<SfProduct> ProductList) {
	    
		int numb=0;
		
		if (ProductList != null) {
		     
			for (SfProduct sfProduct2 : ProductList) {
				
				if (sfProduct2.getCode().equals(sfProjectImport)) {
		                    
					numb++;
				}
			}
			
			return numb;
		}
		
		return numb;
	}

	
	@RequiresPermissions("project:sfProject:edit")
	@RequestMapping(value = "importelement", method = RequestMethod.POST)
	public String importProductFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {

		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<ProductElementImport> list = ei
					.getDataList(ProductElementImport.class);

			SfElement sfElement = null;
			SfProduct sfProduct = null;
			SfProjectProduct sfProjectProduct;
			SfProductElement sfProductElement;
			List<SfElement> sfElementList = null;
			List<SfProduct> sfProductList = null;
			List<SfProjectProduct> sfProjectProductList = null;
			List<SfProductElement> sfProductElementList = null;
			int i = 0;

			for (ProductElementImport productElementImport : list) {
				try {
					boolean isFlag = false;

					/**
					 * 产品编号为空，为无效数据
					 */
					if (StringUtils.isEmpty(productElementImport
							.getProductCode().trim())) {
						// failureMsg.append("<br/>产品编号为空，为无效数据; ");
						continue;
					}

					sfProduct = sfProductService
							.getproduct(productElementImport.getProductCode()
									.trim());

					if (sfProduct != null) {

						sfProduct.setAge(productElementImport.getProductAge()
								.trim());
						sfProduct.setStatus(productElementImport
								.getProductStatus().trim());
						sfProduct.setShipMentCount(productElementImport
								.getShipMentCount().trim());

						sfProductService.save(sfProduct);
						isFlag = true;
					}

					/**
					 * 判断是否需要新增配件
					 */
					if (sfProduct != null
							&& StringUtils.isNotEmpty(productElementImport
									.getElementCode().trim())) {
						/**
						 * 备件编号存在则不创建
						 */
						sfElement = new SfElement();
						sfElement.setCode(productElementImport.getElementCode()
								.trim());
						sfElementList = sfElementService.findList(sfElement);
						if (CollectionUtils.isEmpty(sfElementList)) {
							sfElement.setCode(productElementImport
									.getElementCode().trim());
							sfElement.setContent(productElementImport
									.getElementContent().trim());
							sfElement.setAttributes(productElementImport
									.getElementAttributes().trim());
							sfElement.setNum(productElementImport
									.getNowNumber().trim());
							sfElement.setSafeNum(productElementImport
									.getSafeNumber().trim());
							sfElement.setWarehouse(productElementImport
									.getWarehouse().trim());
							sfElementService.save(sfElement);
							isFlag = true;
						} else {
							sfElement = sfElementList.get(0);
						}
					}

					/**
					 * 判断是否需要新增产品、备件关系
					 */

					if (sfElement != null && sfProduct != null) {
						sfProductElement = new SfProductElement();
						sfProductElement.setProductId(sfProduct.getId());
						sfProductElement.setElementId(sfElement.getId());
						sfProductElementList = sfProductElementService
								.findList(sfProductElement);
						if (CollectionUtils.isEmpty(sfProductElementList)) {
							sfProductElementService.save(sfProductElement);
							isFlag = true;
						}
					}

					if (isFlag) {
						successNum++;
					} else {
						failureMsg.append("<br/>无效数据; " + i);
					}

				} catch (Exception e) {
					e.printStackTrace();
					failureNum++;
				}
				i++;
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条项目，导入信息如下：");
			}
			// addMessage(redirectAttributes,
			// "已成功导入 "+successNum+" 条数据"+failureMsg);

			addMessage(redirectAttributes, "数据导入成功 ");

		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/element/sfElement/list?repage";
	}

	/**
	 * 导入项目图片
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("project:sfProject:edit")
	@RequestMapping(value = "importPic", method = RequestMethod.POST)
	public String importPic(MultipartFile mfile, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {

		/**
		 * 文件存储路径
		 */
		StringBuffer unZipCopyPath = new StringBuffer(request.getSession()
				.getServletContext().getRealPath("/"));
		unZipCopyPath.append("userfiles/").append(UserUtils.getUser().getId())
				.append("/project/images/").append("XXX");
	

		/**
		 * 文件访问路径
		 */
		StringBuffer urlBuffer = new StringBuffer();
		urlBuffer.append(request.getContextPath());
		urlBuffer.append("/userfiles/").append(UserUtils.getUser().getId())
				.append("/project/images/");

		System.out.println("+++++++++++++" + urlBuffer);

		int successNum = 0;// 成功数
		int failureNum = 0;// 失败数

		StringBuilder failureMsg = new StringBuilder();
		String descDir = Config.getConfig("unZip.project.pic");
		FileUtils.createDirectory(descDir);
		String upFilePath = descDir + "/" + mfile.getOriginalFilename();
		try {
			mfile.transferTo(new File(upFilePath));

			this.unZip(descDir + "/", upFilePath);

			String unzipPath = descDir + "/"
					+ mfile.getOriginalFilename().split("\\.")[0];
			File descDirFile = new File(unzipPath);

			String[] fileNames = descDirFile.list();
			FilenameFilter filter = new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					name = name.toLowerCase();
					return name.endsWith(".jpg") || name.endsWith(".png");
				}
			};

			SfProject sfProject;
			SfAttachment sfAttachment;
			List<SfProject> sfProjectList = null;
			for (String fileName : fileNames) {
				if (fileName.split("\\.").length < 1) {
					continue;
				}

				String pic = fileName.substring(0, fileName.lastIndexOf("."));

				sfProject = new SfProject();
				sfProject.setCode(pic);
				sfProjectList = sfProjectService.findList(sfProject);
				if (CollectionUtils.isEmpty(sfProjectList)) {
					failureMsg.append("<br/>项目编号" + fileName + "不存在！; ");
					failureNum++;
					continue;
				}
				sfProject = sfProjectList.get(0);
				File descDirPicFile = new File(unzipPath + "/" + fileName);

				FileUtils.copyFile(descDirPicFile.getAbsolutePath(),
						unZipCopyPath.toString().replace("XXX", fileName));
				sfAttachment = new SfAttachment();
				sfAttachment.setObjectId(sfProject.getId());
				sfAttachment.setUrl(urlBuffer.toString()
						+ descDirPicFile.getName());
				sfAttachmentService.save(sfAttachment);
				
				sfProject.setExistImage("已有");
				
				sfProjectService.save(sfProject);

				successNum++;
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条项目，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条项目"
					+ failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}

		FileUtils.deleteDirectory(descDir);
		return "redirect:" + adminPath + "/project/sfProject/list?repage";
	}

	
	
	
	
	
	
	@SuppressWarnings("rawtypes")
	private void unZip(String descDir, String upFilePath) throws IOException {
		ZipFile zip = new ZipFile(upFilePath, "GBK");
		for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
			logger.debug(outPath);

			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		zip.close();
		logger.debug("******************解压完毕********************");
	}




	@RequiresPermissions("project:sfProject:view")
	@RequestMapping(value = "batchDeletes")
	public void batchDeletes( HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		List<String> delList = batch_deletion(request);

		try {
			sfProjectService.batchDeletes(delList);
		} catch (Exception e) {
			logger.error("删除失败");

		}
		
		
		
	}

	

	
	/**
	 * 
	 * batch_deletion:(批量删除，把前台的字符串截取为list对象)
	 * 
	 * @param request
	 * @return 返回删除的集合
	 */
	private List<String> batch_deletion(HttpServletRequest request) {
		String items = request.getParameter("delitems");

		List<String> delList = new ArrayList<String>();
		String[] strs = items.split(",");
		for (String str : strs) {
			delList.add(str);
		}
		return delList;
	}
	
}